package com.zzy.service.impl;

import com.zzy.model.User;
import com.zzy.repository.UserRepository;
import com.zzy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> getAll(){
        return userRepository.findAll();
    }

    @Override
    public List<User> findByName(String name){
        List<User> userList1 = userRepository.findByName1(name);
        List<User> userList2 = userRepository.findByName2(name);
        List<User> userList3 = userRepository.findByNameAndAddress(name, "3");
        System.out.println("userList1:" + userList1);
        System.out.println("userList2:" + userList2);
        System.out.println("userList3:" + userList3);
        return userRepository.findByName(name);
    }



    @Override
    public void saveUser(User book){
        userRepository.save(book);
    }

    @Override
    @Cacheable("users")
    public User findOne(String id){
        User user = new User();
        user.setId(id);
        return findModelByParam( user);
    }

    @Override
    public User findModelByParam(User user) {
        if(user==null){
            user = new User();//保证不报错
        }
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                //组合查询条件开始 contains  startsWith  endsWith
                .withMatcher("id", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("address", ExampleMatcher.GenericPropertyMatchers.contains())
                .withIgnoreCase()  //忽略大小写查询
                .withIgnoreNullValues() ;//忽略 null 值 对 int 类型 无效 因此 int 使用 Integer
        Example<User> e = Example.of(user, matcher);
        return userRepository.findOne(e).get();
    }

    @Override
    public void delete(String id){
        User user = new User();
        user.setId(id);
        userRepository.delete(user);
    }

}